<?php
require_once(_PS_MODULE_DIR_.'prestatheme/controllers/admin/AdminPrestathemeEditorController.php');
require_once(_PS_MODULE_DIR_.'prestatheme/models/ConfigItem.php');

class AdminConfigItemController extends ModuleAdminController
{
    protected $configTab;
    protected $configParentItem;
    
	public function __construct()
	{
		$this->table      = 'pt_config_item';
		$this->identifier = 'id_item';
		$this->className  = 'ConfigItem';
		$this->lang       = true;
		
		$this->context = Context::getContext();
		
		$this->addRowAction('view');
		$this->addRowAction('edit');
		$this->addRowAction('delete');
		
		$this->bulk_actions = array(
			'delete' => array(
				'text' => $this->l('Delete selected'), 
				'confirm' => $this->l('Delete selected items?')
			)
		);

		$this->_select = '
		    CONCAT(c.`code`, \' \', c.`version`) AS `editor`,
            tl.label AS `tab_label`,
            il.label AS `parent_label`';

		$this->_join = '
    		LEFT JOIN `'._DB_PREFIX_.'pt_config_tab` t ON (t.`id_tab` = a.`id_tab`)
    		LEFT JOIN `'._DB_PREFIX_.'pt_config_tab_lang` tl ON (a.`id_tab` = tl.`id_tab` AND tl.`id_lang` = '.(int)$this->context->language->id.')
    		LEFT JOIN `'._DB_PREFIX_.'pt_config_item` i ON (i.`id_item` = a.`id_parent`)
    		LEFT JOIN `'._DB_PREFIX_.'pt_config_item_lang` il ON (a.`id_parent` = il.`id_item` AND il.`id_lang` = '.(int)$this->context->language->id.')
    		LEFT JOIN `'._DB_PREFIX_.'pt_theme_editor` e ON (e.`id_editor` = t.`id_editor`)
    		LEFT JOIN `'._DB_PREFIX_.'pt_cms` c ON (c.`id_cms` = e.`id_cms`)
    		LEFT JOIN `'._DB_PREFIX_.'pt_cms_lang` cl ON (c.`id_cms` = cl.`id_cms` AND cl.`id_lang` = '.(int)$this->context->language->id.')';
		
		$this->fields_list = array(
			'id_item' => array(
				'title' => $this->l('ID'), 
				'align' => 'center', 
				'width' => 25
			),
			'label' => array(
				'title' => $this->l('Item name'), 
				'align' => 'center', 
                'lang'  => true
			),
			'tab_label' => array(
				'title' => $this->l('Parent Tab'), 
				'align' => 'center', 
			),
			'parent_label' => array(
				'title' => $this->l('Parent Item'), 
				'align' => 'center', 
			),
			'editor' => array(
				'title' => $this->l('Target CMS'), 
				'align' => 'center', 
			),
            'position' => array(
                'title' => $this->l('Position'),
                'width' => 40,
                'filter_key' => 'position',
                'align' => 'center',
                'position' => 'position'
            ),
            'date_add' => array(
                'title' 	=> $this->l('Created On'),
                'type' 	=> 'date'
            ),
            'date_upd' => array(
                'title' 	=> $this->l('Last update On'),
                'type' 	=> 'date'
            ),
			'active' => array(
				'title' => $this->l('Enabled'), 
				'width' => 25, 
				'align' => 'center', 
				'active' => 'status', 
				'type' => 'bool', 
				'orderby' => false
			),
		);
        
        /*
		// The controller can't be call directly
		// In this case, AdminPrestathemeEditorController::getCurrentTab() is null
		if (!AdminPrestathemeEditorController::getCurrentTab())
		{
			$this->redirect_after = '?controller=AdminPrestathemeEditor&token='.Tools::getAdminTokenLite('AdminPrestathemeEditor');
			$this->redirect();
		}
        */

		$this->configTab = AdminPrestathemeEditorController::getCurrentTab();
        if (!empty($this->configTab->id))
            $this->_filter = ' AND a.`id_tab` = '.(int)$this->configTab->id;
            
		$this->configItem = AdminPrestathemeEditorController::getCurrentItem();
        if (!empty($this->configItem->id))
            $this->_filter = ' AND a.`id_parent` = '.(int)$this->configItem->id;
        
		parent::__construct();
	}
    
    public function setIdTabForFilter ($id_tab) {
        $this->_filter = 'AND a.`id_tab` = '.(int)$id_tab;
    }
    
    public function setIdParentForFilter ($id_parent) {
        $this->_filter = 'AND a.`id_parent` = '.(int)$id_parent;
    }

	/**
	 * AdminController::initContent() override
	 * @see AdminController::initContent()
	 */
	public function initContent()
	{
		// toolbar (save, cancel, new, ..)
		$this->initToolbar();
		if ($this->display == 'edit' || $this->display == 'add')
		{
			if (!($this->object = $this->loadObject(true)))
				return;
			$this->content .= $this->renderForm();
		}
		else if ($this->display == 'editAttributes')
		{
			if (!$this->object = new Attribute((int)Tools::getValue('id_attribute')))
				return;

			$this->content .= $this->renderFormAttributes();
		}
		else if ($this->display != 'view' && !$this->ajax)
		{
			$this->content .= $this->renderList();
			$this->content .= $this->renderOptions();
		}

		$this->context->smarty->assign(array(
			'table' => $this->table,
			'current' => self::$currentIndex,
			'token' => $this->token,
			'content' => $this->content,
			'url_post' => self::$currentIndex.'&token='.$this->token,
		));
	}

	public function initToolbar()
	{
        parent::initToolbar();
        $this->toolbar_scroll = false;
		switch ($this->display)
		{
			// @todo defining default buttons
			case 'add':
			case 'edit':
				// Default save button - action dynamically handled in javascript
				$this->toolbar_btn['save'] = array(
					'href' => '#',
					'desc' => $this->l('Save')
				);
                
                $back = null;
                if (!empty($this->configTab->id)) {
            		$back = self::$currentIndex.'&id_tab='. $this->configTab->id .'&token='.$this->token;
            		$this->toolbar_btn['back'] = array(
    					'href' => $back,
    					'desc' => $this->l('Back to the tab')
    				);
                }
                
                if (!empty($this->configParentItem->id)) {
                    $back = self::$currentIndex.'&id_item='. $this->configParentItem->id .'&token='.$this->token;
    				$this->toolbar_btn['backparent'] = array(
    					'href' => $back,
    					'desc' => $this->l('Back to the parent'),
                        'class'=> 'process-icon-back'
    				);
                }
                
                if (empty($back))
                    unset($this->toolbar_btn['back']);
                
				break;
			default: // list, default
                break;
		}
	}

	public function initToolbarTitle()
	{
		$bread_extended = $this->breadcrumbs;

		switch ($this->display)
		{
			case 'edit':
				$bread_extended[] = $this->l('Edit this item');
				break;

			case 'add':
				$bread_extended[] = $this->l('Add new item');
				break;
		}

		$this->toolbar_title = $bread_extended;
	}

	/**
	 * Modifying initial getList method to display position feature (drag and drop)
	 */
	public function getList($id_lang, $order_by = null, $order_way = null, $start = 0, $limit = null, $id_lang_shop = false)
	{
		if ($order_by && $this->context->cookie->__get($this->table.'Orderby'))
			$order_by = $this->context->cookie->__get($this->table.'Orderby');
		else
			$order_by = 'position';

		parent::getList($id_lang, $order_by, $order_way, $start, $limit, $id_lang_shop);
	}
	
	public function renderForm()
	{
		$this->fields_form = array(
			'tinymce' => true,
			'legend' => array(
				'title' => $this->l('Available CMS for prestatheme'),
				'image' => '../img/admin/cog.gif'
			),
			'input' => array(
				array(
					'type' => 'select',
					'label' => $this->l('Tab'),
					'name' => 'id_tab',
					'required' => true,
					'options' => array(
						'query' => ConfigTab::getConfigTabs(true/*, ' AND t.`id_editor` = '*/),
						'id' => 'id_tab',
						'name' => 'fullname',
						'default' => array('value'=>'','label'=>$this->l('None')),
					),
					'desc' => $this->l('Select the associated tab if parent item will not set')
				),
				array(
					'type' => 'select',
					'label' => $this->l('Parent item'),
					'name' => 'id_parent',
					'required' => true,
					'options' => array(
						'query' => ConfigItem::getConfigItems(true/*, ' AND t.`id_editor` = '*/),
						'id' => 'id_item',
						'name' => 'fullname',
						'default' => array('value'=>'','label'=>$this->l('None')),
					),
					'desc' => $this->l('Select the associated parent if tab is not set')
				),
				array(
					'type' => 'text',
					'label' => $this->l('Label'),
					'name' => 'label',
					'size' => 33,
					'lang' => true,
					'required' => true,
					'hint' => $this->l('Forbidden characters:').' <>;=#{}',
					'desc' => $this->l('The label to be displayed in the theme editor interface.')
				),
				array(
					'type' => 'text',
					'label' => $this->l('Name'),
					'name' => 'name',
					'size' => 33,
					'required' => true,
					'hint' => $this->l('Invalid characters:').' <>;=#{}'
				),
				array(
					'type' => 'textarea',
					'label' => $this->l('Description'),
					'name' => 'description',
					'autoload_rte' => true,
					'lang' => true,
					'rows' => 5,
					'cols' => 40,
					'hint' => $this->l('Forbidden characters:').' <>;=#{}',
					'desc' => $this->l('About the features enabled by this tab.')
				),
				array(
					'type' => 'radio',
					'label' => $this->l('Available'),
					'name' => 'active',
					'required' => false,
					'class' => 't',
					'is_bool' => true,
					'values' => array(
						array(
							'id' => 'active_on',
							'value' => 1,
							'label' => $this->l('Enabled')
						),
						array(
							'id' => 'active_off',
							'value' => 0,
							'label' => $this->l('Disabled')
						)
					),
				),
				array(
					'type' => 'text',
					'label' => $this->l('Iso Lang'),
					'name' => 'lang_iso',
					'size' => 33,
					'readonly' => true,
					'required' => true,
					'lang' => true,
					'desc' => $this->l('This field is authomaticaly fill.'),
				),
			),
			'submit' => array(
				'title' => $this->l('   Save   '),
				'class' => 'button'
			)
		);
        $languages = Language::getLanguages(false);
        $this->fields_value['lang_iso'] = array();
        foreach ($languages AS $lang)
        {
            $this->fields_value['lang_iso'][$lang['id_lang']] = $lang['iso_code'];
        }

		if (!($obj = $this->loadObject(true)))
			return;

		return parent::renderForm();
	}

	public function renderView()
	{
		if (!($object = $this->loadObject()))
			return;
			
		$this->tpl_view_vars = array(
			'id_lang' => Context::getContext()->language->id,
			'object' => $object,
			'head_title' => ($object->id ? $object->getCMSName() : $this->l('New CMS to be avaible on Prestatheme')),
			'shopContext' => Shop::getContext(),
		);

		return parent::renderView();
	}
}